//
//  BasePublicMethord.m
//  duoErMei
//
//  Created by Jack's Mac on 2016/12/29.
//  Copyright © 2016年 Jack. All rights reserved.
//   公共方法

#import "BasePublicMethord.h"

#import <UIKit/UIKit.h>

//#import "NSString+StringToWords.h"

@implementation BasePublicMethord

+ (CGRect)getSize:(NSString *)str fontSize:(CGFloat)font weith:(CGFloat)weith{
    
    
    CGRect labelSize = [str boundingRectWithSize:CGSizeMake(weith, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:font],NSFontAttributeName, nil] context:nil];
    
    return labelSize;
    
    
}



//返回时间差
+ (NSString *)intervalSinceNow: (NSString *) theDate
{
    NSArray *timeArray=[theDate componentsSeparatedByString:@"."];
    theDate=[timeArray objectAtIndex:0];
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd"];
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate date];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=late-now;
    
    if (cha/3600<1) {//fenzhong
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@", timeString];
        
    }
    if (cha/3600>1&&cha/86400<1) {//小时
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@", timeString];
    }
    if (cha/86400>1)//天数
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@", timeString];
        
    }
    return timeString;
}

//随机数生成方法
+(NSInteger)getRandomNumber:(NSInteger)from to:(NSInteger)to
{
    return (NSInteger)(from + (arc4random() % (to - from + 1)));
}


/**
 *  生成一个numcount位的随机数
 *
 *  @param Numcount <#Numcount description#>
 *
 *  @return <#return value description#>
 */
+ (NSString *)returnSuijiNumWithcount:(NSInteger)Numcount from:(NSInteger)startNum To:(NSInteger)endNum{
    
    NSString *Str1 = [NSString stringWithFormat:@"%ld", (startNum + (arc4random() % (endNum - startNum + 1)))];
    for (NSInteger i = 0; i<Numcount-1; i++) {
        Str1 = [Str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", (startNum + (arc4random() % (endNum - startNum + 1)))]];
    }
    NSLog(@"随机shu》》》》%@", Str1);
    return Str1;
    
}
//,没有使用代理的提示框,,有参数传递
+(void)showAlviewUI:(NSString *)showMessageString {
    UIAlertView *showAlview = [[UIAlertView alloc] initWithTitle:@"提示" message:showMessageString delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [showAlview show];
}
//获取时间戳数据
//获取时间戳
+ (NSString *)getDataString {
    //获取当前时间
    
    NSDate * today = [NSDate date];
    
    //NSLog(@"%@",today);
    
    //    打印出来是“2014-07-16 07:54:36 +0000”
    //
    //    很奇怪？现在明明是2014-07-16 15:54:36啊
    //
    //    因为存在不同时区，系统默认格林尼治时间
    //
    //    所以就要转换时间格式了
    
    //转换时间格式
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];//格式化
    //    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];获取到秒
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];//获取到毫秒
    
    NSString * s1 = [df stringFromDate:today];
    
    //NSLog(@" s1s1s1s%@",s1);
    
    //    打印出来是“2014-07-16 15:54:36”
    //
    //    现在已经获取到当前的时间
    //
    //    这样还没有完呢，需要转换成一个字符串，类似“20140716052021”的时间戳
    
    NSDate * date = [df dateFromString:s1];
    
    //转换时间格式
    
    NSDateFormatter *df2 = [[NSDateFormatter alloc] init];//格式化
    
    [df2 setDateFormat:@"yyyyMMddHHmmssSSS"];
    
    [df2 setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    NSLog(@"%@",[df2 stringFromDate:date]);
    return [df2 stringFromDate:date];
}

//获取一个时间点字符串
+(NSString *)getTimeDataPointString{
    //获取当前时间
    
    NSDate * today = [NSDate date];
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];//格式化
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString * s1 = [df stringFromDate:today];
    return s1;
}
//把json字符串转化成数组或者字典
+(id)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization
                     JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments
                     error:&error];
    if (jsonObject != nil && error == nil){
       // NSLog(@"反序列化成功...");
        if ([jsonObject isKindOfClass:[NSDictionary class]]){
            NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
            //NSLog(@"反序列化后的dictionary数据 = %@", deserializedDictionary);
            return deserializedDictionary;
        }
        else if ([jsonObject isKindOfClass:[NSArray class]]){
            NSArray *deserializedArray = (NSArray *)jsonObject;
           // NSLog(@"反序列化json后的数组 = %@", deserializedArray);
            return deserializedArray;
        }else {
            return nil;
        }
        
    }else{
        NSLog(@"%@", error);
        NSLog(@"反序列化时发生一个错误");
        return nil;
    }
    
}
// 根据图片url获取图片尺寸
+(CGSize)getImageSizeWithURL:(id)imageURL
{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero;                  // url不正确返回CGSizeZero
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
    
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size =  [self getPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size =  [self getGIFImageSizeWithRequest:request];
    }
    else{
        size = [self getJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size))                    // 如果获取文件头信息失败,发送异步请求请求原图
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
            size = image.size;
        }
    }
    return size;
}

//  获取PNG图片的大小
+(CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 8)
    {
        int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        [data getBytes:&w3 range:NSMakeRange(2, 1)];
        [data getBytes:&w4 range:NSMakeRange(3, 1)];
        int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
        int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        [data getBytes:&h1 range:NSMakeRange(4, 1)];
        [data getBytes:&h2 range:NSMakeRange(5, 1)];
        [data getBytes:&h3 range:NSMakeRange(6, 1)];
        [data getBytes:&h4 range:NSMakeRange(7, 1)];
        int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取gif图片的大小
+(CGSize)getGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取jpg图片的大小
+(CGSize)getJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if ([data length] <= 0x58) {
        return CGSizeZero;
    }
    
    if ([data length] < 210) {// 肯定只有一个DQT字段
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
        short w = (w1 << 8) + w2;
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
        short h = (h1 << 8) + h2;
        return CGSizeMake(w, h);
    } else {
        short word = 0x0;
        [data getBytes:&word range:NSMakeRange(0x15, 0x1)];
        if (word == 0xdb) {
            [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
            if (word == 0xdb) {// 两个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            } else {// 一个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            }
        } else {
            return CGSizeZero;
        }
    }
}
//判断邮箱
+(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}



//判断手机号码
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,177
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188, 183
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[123478]|7[0-9]|6[0-9]|9[0-9])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186 145
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189  181, 177
     22         */
    NSString * CT = @"^1((33|53|77|8[019])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


//把数组转化成json格式的字符串
+(NSString *)jsonArraytoJsonStr:(NSArray *)array{
    NSData *data=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    jsonStr= [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
//    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    //    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"]" withString:@""];
    //    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"[" withString:@""];
    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    return jsonStr;
}

//把数组转化成json格式的字符串dierzhong 
+(NSString *)jsonArraytoJsonStrTwo:(NSArray *)array{
    NSData *data=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    jsonStr= [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    //    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"]" withString:@""];
        jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"[" withString:@""];
    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    return jsonStr;
}


+(NSString *)returnJsonStrFromJsonArr:(NSArray *)array {
    NSData *data=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    jsonStr= [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"\"" withString:@"'"];
    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"]" withString:@""];
    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"[" withString:@""];
    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    jsonStr= [jsonStr stringByReplacingOccurrencesOfString:@"," withString:@","];
    return jsonStr;
    
}

// 字典转json字符串方法

+(NSString *)convertToJsonData:(NSDictionary *)dict
{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}


//base64转码
+(NSString *)imageBase64WithDataURL:(UIImage *)image

{
    NSData *imageData =nil;
    NSString *mimeType =nil;
    
    //图片要压缩的比例，此处100根据需求，自行设置
    CGFloat x =100 / image.size.height;
    if (x >1)
        
    {
        
        x = 1.0;
        
    }
    
    imageData = UIImageJPEGRepresentation(image, x);
    
    mimeType = @"image/jpeg";
    
    //    return [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, [imageData base64EncodedStringWithOptions:0]];
    return [imageData base64EncodedStringWithOptions:0];
    
}

/*  生成商品订单号  */
+ (NSString *)generateTradeNo{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYYMMddhhmmss"];
    return [formatter stringFromDate:date];
}



//获取两个日期的时间间隔
+(NSString *)getDataTimeform:(NSString *)showTimeStr {
    //首先创建格式化对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    //然后创建日期对象
    NSDate *date1 = [dateFormatter dateFromString:showTimeStr];//@"2020-10-31 00:00:00"];
    NSDate *date = [NSDate date];
    //计算时间间隔（单位是秒）
    NSTimeInterval time = [date timeIntervalSinceDate:date1];
    //计算天数、时、分、秒
    int days = ((int)time)/(3600*24);
    int hours = ((int)time)%(3600*24)/3600;
    int minutes = ((int)time)%(3600*24)%3600/60;
    int seconds = ((int)time)%(3600*24)%3600%60;
    //NSString *dateContent = [[NSString alloc] initWithFormat:@"仅剩%i天%i小时%i分%i秒",days,hours,minutes,seconds];
    //（%i可以自动将输入转换为十进制,而%d则不会进行转换）
    if (days!=0) {
        return [NSString stringWithFormat:@"%i天前", days];
    }else if (days == 0&&hours!=0) {
        return [NSString stringWithFormat:@"%i小时前", hours];
    }else if (days == 0&&hours==0&&minutes!=0) {
        return [NSString stringWithFormat:@"%i分钟前", minutes];
    }else {//if (days == 0&&hours==0&&minutes==0&&seconds!=0) {
         return [NSString stringWithFormat:@"%i秒前", seconds];
    }
}

//获取两个日期的时间间隔(返回大致时间, 精确到天),, 返回分钟
+(int)getDayTimeform:(NSString *)showTimeStr anotherBigtime:(NSString *)bigTimeStr{
    //首先创建格式化对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    //然后创建日期对象
    NSDate *date1 = [dateFormatter dateFromString:showTimeStr];
    
    //首先创建格式化对象
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm"];
    //然后创建日期对象
    NSDate *date2 = [dateFormatter dateFromString:bigTimeStr];
    
    
    
//    NSDate *date = [NSDate date];
    //计算时间间隔（单位是秒）
    NSTimeInterval time = [date1 timeIntervalSinceDate:date2];
    //计算天数、时、分、秒
    int days = ((int)time)/(3600*24);
    int hours = ((int)time)%(3600*24)/3600;
    int minutes = ((int)time)%(3600*24)%3600/60;
//    int seconds = ((int)time)%(3600*24)%3600%60;
    //NSString *dateContent = [[NSString alloc] initWithFormat:@"仅剩%i天%i小时%i分%i秒",days,hours,minutes,seconds];
    //（%i可以自动将输入转换为十进制,而%d则不会进行转换）
    int temp = minutes+hours*60+days*24*60;
    if (temp<0) {
        temp = temp*(-1);
    }
    
    return temp;//[NSString stringWithFormat:@"%i", days];
}


//获取两个日期的时间间隔(返回大致时间, 有文字)
+(NSString *)getDayTimeStringform:(NSString *)showTimeStr anotherBigtime:(NSString *)bigTimeStr{
    //首先创建格式化对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    //然后创建日期对象
    NSDate *date1 = [dateFormatter dateFromString:showTimeStr];
    
    //首先创建格式化对象
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm"];
    //然后创建日期对象
    NSDate *date2 = [dateFormatter dateFromString:bigTimeStr];
    
    
    
    //    NSDate *date = [NSDate date];
    //计算时间间隔（单位是秒）
    NSTimeInterval time = [date1 timeIntervalSinceDate:date2];
    //计算天数、时、分、秒
    int days = ((int)time)/(3600*24);
    int hours = ((int)time)%(3600*24)/3600;
    int minutes = ((int)time)%(3600*24)%3600/60;
    if (days<0) {
        days = days*(-1);
    }
    if (hours<0) {
        hours = hours*(-1);
    }
    if (minutes<0) {
        minutes = minutes*(-1);
    }
    
    
    //    int seconds = ((int)time)%(3600*24)%3600%60;
    NSString *dateContent = [[NSString alloc] initWithFormat:@"(%i天%i小时%i分)",days,hours,minutes];
    //（%i可以自动将输入转换为十进制,而%d则不会进行转换）
    return dateContent;

}

//获取两个日期的时间间隔(返回大致时间字典)
+(NSDictionary *)getDayTimeDicform:(NSString *)showTimeStr anotherBigtime:(NSString *)bigTimeStr{
    //首先创建格式化对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    //然后创建日期对象
    NSDate *date1 = [dateFormatter dateFromString:showTimeStr];
    
    //首先创建格式化对象
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm"];
    //然后创建日期对象
    NSDate *date2 = [dateFormatter dateFromString:bigTimeStr];
    
    
    
    //    NSDate *date = [NSDate date];
    //计算时间间隔（单位是秒）
    NSTimeInterval time = [date1 timeIntervalSinceDate:date2];
    //计算天数、时、分、秒
    int days = ((int)time)/(3600*24);
    int hours = ((int)time)%(3600*24)/3600;
    int minutes = ((int)time)%(3600*24)%3600/60;
    if (days<0) {
        days = days*(-1);
    }
    if (hours<0) {
        hours = hours*(-1);
    }
    if (minutes<0) {
        minutes = minutes*(-1);
    }
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dic setValue:[NSString stringWithFormat:@"%d", days] forKey:@"day"];
    [dic setValue:[NSString stringWithFormat:@"%d", hours] forKey:@"hour"];
    [dic setValue:[NSString stringWithFormat:@"%d", minutes] forKey:@"minutes"];
    return dic;
}


//获取当前日期N天(前或者后)的日期(1是后  0是前)
+(NSString *)getDatafromCount:(NSInteger )dayCount addOrReduce:(NSString *)judge {
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    if(dayCount!=0) {
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        if ([judge isEqual:@"1"]) {
            theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*dayCount];
        } else {
        theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*dayCount];
        }
    } else {
        theDate = nowDate;
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY.MM.dd"];
    return [formatter stringFromDate:theDate];
}

/**
 拨打电话
 
 @param phoneNum        电话号码
 @param telephoningType 拨打类型 见TKCTelephoningType
 */
+ (void)userTelephoningNum:(NSString *)phoneNum type:(TKCTelephoningType)telephoningType{
    
    switch (telephoningType) {
        case TKCTelephoningTypeApplicationWebView:
        {
            phoneNum = [@"tel:" stringByAppendingString:phoneNum];
            //
            UIWebView *webView = [[UIWebView alloc] init];
            [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:phoneNum]]];
            [[UIApplication sharedApplication].keyWindow addSubview:webView];
        }
            break;
        case TKCTelephoningTypeApplication:
        {
            phoneNum = [@"tel:" stringByAppendingString:phoneNum];
            //
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNum]];
        }
            break;
        case TKCTelephoningTypeApplicationTelprompt:
        {
            phoneNum = [@"telprompt://" stringByAppendingString:phoneNum];
            //
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNum]];
        }
            break;
            
        default:
            break;
    }
    
}


//数组排序(从小到大排序)
+(NSArray *)returnSortArrayFromArray:(NSArray *)tempArray {
    
    NSMutableArray *sortArr = [[NSMutableArray alloc] initWithArray:tempArray];
    for (int i = 0; i < sortArr.count - 1; i++) {
        //比较的躺数
        for (int j = 0; j < sortArr.count - 1 - i; j++) {
            //比较的次数
            if ([sortArr[j] intValue] > [sortArr[j + 1] intValue]) {
                //这里为升序排序
                int temp = [sortArr[j] intValue];
                sortArr[j] = sortArr[j + 1];
                //OC中的数组只能存储对象，所以这里转换成string对象
                sortArr[j + 1] = [NSString stringWithFormat:@"%d",temp];
            }
        }
    }
    return sortArr;
    
}

//MD5加密
+(NSString *)md5:(NSString *)inPutText{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

+ (float) heightForString:(NSString *)value andWidth:(float)width{
    //获取当前文本的属性
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:value];
    NSRange range = NSMakeRange(0, attrStr.length);
    // 获取该段attributedString的属性字典
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];
    // 计算文本的大小
    CGSize sizeToFit = [value boundingRectWithSize:CGSizeMake(width - 16.0, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                        attributes:dic        // 文字的属性
                                           context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    return sizeToFit.height + 16.0;
}

//计算year年month月第一天是星期几，周日则为0
+(int)GetTheWeekOfDayByYera:(int)year andByMonth:(int)month{
    int numWeek = ((year-1)+ (year-1)/4-(year-1)/100+(year-1)/400+1)%7;//numWeek为years年的第一天是星期几
    //NSLog(@"%d",numWeek);
    int ar[12] = {0,31,59,90,120,151,181,212,243,273,304,334};
    int numdays = (((year/4==0&&year/100!=0)||(year/400==0))&&(month>2))?(ar[month-1]+1):(ar[month-1]);//numdays为month月years年的第一天是这一年的第几天
    //NSLog(@"%d",numdays);
    int dayweek = (numdays%7 + numWeek)%7;//month月第一天是星期几，周日则为0
    //NSLog(@"%d",dayweek);
    return dayweek;
    
}

//获取当前时间数据字典格式分开的数据形式
+(NSDictionary *)getNowDataDic{
    NSDate *  senddate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd-HH:mm"];
    
    NSDateFormatter  *dateformatter1 = [[NSDateFormatter alloc] init];
    [dateformatter1 setDateFormat:@"YYYY-MM-dd-HH-mm"];
    
    
    
    NSString *locationString=[dateformatter stringFromDate:senddate];
    NSArray *dataarray = [locationString componentsSeparatedByString:@"-"];
    
    NSString *locationString1=[dateformatter1 stringFromDate:senddate];
    NSArray *dataarray1 = [locationString1 componentsSeparatedByString:@"-"];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dic setValue:dataarray[0] forKey:@"year"];
    [dic setValue:dataarray[1] forKey:@"month"];
    [dic setValue:dataarray[2] forKey:@"day"];
    [dic setValue:dataarray[3] forKey:@"time"];
    [dic setValue:dataarray1[3] forKey:@"hour"];
    [dic setValue:dataarray1[4] forKey:@"second"];
    
    return dic;
}
//获取具体的某一天是周几(第几天, 周日是1)
+(NSInteger )returnWeekDayIntFormyear:(NSString *)year month:(NSString *)month day:(NSString *)day {
    NSDateComponents *_comps = [[NSDateComponents alloc] init];
    [_comps setDay:[day intValue]];
    [_comps setMonth:[month intValue]];
    [_comps setYear:[year intValue]];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *_date = [gregorian dateFromComponents:_comps];
    NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:_date];
    NSInteger _weekday = [weekdayComponents weekday];
    return _weekday;
}

//获取具体的莫一天是周几字符类型
+(NSString *)returnWeekDayStrFormyear:(NSString *)year month:(NSString *)month day:(NSString *)day{
    NSDateComponents *_comps = [[NSDateComponents alloc] init];
    [_comps setDay:[day intValue]];
    [_comps setMonth:[month intValue]];
    [_comps setYear:[year intValue]];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *_date = [gregorian dateFromComponents:_comps];
    NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:_date];
    NSInteger _weekday = [weekdayComponents weekday];
    NSArray *weekArr = @[@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六"];
    return weekArr[_weekday-1];
}




+(NSString *)returnStrAddZeorFromStr:(NSString *)string {
   
    NSString *testStr = string;
    
    if ([testStr integerValue]<10) {
        testStr = [NSString stringWithFormat:@"0%ld", [testStr integerValue]];
    }
    return testStr;
}



+ (UIColor *)getColor:(NSString *)hexColor {
    NSString *string = [hexColor substringFromIndex:1];//去掉#号
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    /* 调用下面的方法处理字符串 */
    red = [self stringToInt:[string substringWithRange:range]];
    
    range.location = 2;
    green = [self stringToInt:[string substringWithRange:range]];
    range.location = 4;
    blue = [self stringToInt:[string substringWithRange:range]];
    
    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}

+ (int)stringToInt:(NSString *)string {
    
    unichar hex_char1 = [string characterAtIndex:0]; /* 两位16进制数中的第一位(高位*16) */
    int int_ch1;
    if (hex_char1 >= '0' && hex_char1 <= '9')
        int_ch1 = (hex_char1 - 48) * 16;   /* 0 的Ascll - 48 */
    else if (hex_char1 >= 'A' && hex_char1 <='F')
        int_ch1 = (hex_char1 - 55) * 16; /* A 的Ascll - 65 */
    else
        int_ch1 = (hex_char1 - 87) * 16; /* a 的Ascll - 97 */
    unichar hex_char2 = [string characterAtIndex:1]; /* 两位16进制数中的第二位(低位) */
    int int_ch2;
    if (hex_char2 >= '0' && hex_char2 <='9')
        int_ch2 = (hex_char2 - 48); /* 0 的Ascll - 48 */
    else if (hex_char1 >= 'A' && hex_char1 <= 'F')
        int_ch2 = hex_char2 - 55; /* A 的Ascll - 65 */
    else
        int_ch2 = hex_char2 - 87; /* a 的Ascll - 97 */
    return int_ch1+int_ch2;
}


//密码判断(至少八位, 必须包含字母和数字)
+(BOOL)judgePasswordWith:(NSString *)transStr {
    BOOL result = NO;
    if ([transStr length] >= 8){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:transStr];
    }
    return result;
}


//根据车牌号显示车辆的限行问题
//+(NSString *)getXXStringWith:(NSString *)provinceStr number:(NSString *)numberStr {
//    if ([provinceStr isEqual:@"浙A"]) {
//        NSArray *wordArr= [numberStr words];
//        NSInteger h = wordArr.count-1;
//        
//        NSString *returnStr = @"";
//        for (NSInteger i= wordArr.count-1; i>=0; i--) {
//            if ([self isPureInt:wordArr[h]]== YES) {
//                if (([wordArr[i] integerValue]== 1)||([wordArr[i] integerValue]== 9)) {
//                    returnStr= @"周一限行";
//                }
//                if (([wordArr[i] integerValue]== 2)||([wordArr[i] integerValue]== 8)) {
//                    returnStr= @"周二限行";
//                }
//                if (([wordArr[i] integerValue]== 3)||([wordArr[i] integerValue]== 7)) {
//                    returnStr= @"周三限行";
//                }
//                if (([wordArr[i] integerValue]== 4)||([wordArr[i] integerValue]== 6)) {
//                    returnStr= @"周四限行";
//                }
//                if (([wordArr[i] integerValue]== 5)||([wordArr[i] integerValue]== 0)) {
//                    returnStr= @"周五限行";
//                }
//                
//            }else {
//                h--;
//            }
//        }
//        return returnStr;
//    }else {
//        return @"外地限行";
//    }
//}

// 此方法是用来判断一个字符串是不是整型.如果传进的字符串是一个字符,可以用来判断它是不是数字
+ (BOOL)isPureInt:(NSString *)string{
    NSScanner *scan = [NSScanner scannerWithString:string];
    int value;
    return [scan scanInt:&value] && [scan isAtEnd];
}


/**
 * 开始到结束的时间差
 */
+ (NSString *)dateTimeDifferenceWithEndTime:(NSString *)endTime{
    NSDateFormatter *date = [[NSDateFormatter alloc]init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *startD =[NSDate date];
    NSDate *endD = [date dateFromString:endTime];
    NSTimeInterval start = [startD timeIntervalSince1970]*1;
    NSTimeInterval end = [endD timeIntervalSince1970]*1;
    NSTimeInterval value = end - start;
    int second = (int)value %60;//秒
    int minute = (int)value /60%60;
    int house = (int)value / (24 * 3600)%3600;
    int day = (int)value / (24 * 3600);
    NSString *str;
    if (day != 0) {
        str = [NSString stringWithFormat:@"%d天%d小时%d分",day,house,minute];//[NSString stringWithFormat:@"耗时%d天%d小时%d分%d秒",day,house,minute,second];
    }else if (day==0 && house != 0) {
        str = [NSString stringWithFormat:@"%d小时%d分",house,minute];
    }else if (day== 0 && house== 0 && minute!=0) {
        str = [NSString stringWithFormat:@"%d分",minute];
    }
    //    else{
    //        str = [NSString stringWithFormat:@"耗时%d秒",second];
    //    }
    return str;
}



//身份证号验证
+ (BOOL)checkValid:(NSString*)tarStr{
    return [self checkUserIdCard:tarStr];
}

/**
 * 判断身份证号码是否合法
 * 位数 15 ~18 位
 * 最后一位可以输入 'X'
 */
#pragma 正则匹配用户身份证号15或18位
+(BOOL)checkUserIdCard: (NSString *) idCard
{
    NSString *pattern = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:idCard];
    if(isMatch){
        
        idCard = [idCard substringToIndex:2];
        int carNum = [idCard intValue];
        return [self binary_search:carNum];
    }
    NSString *tempBool = [NSString stringWithFormat:@"%d", isMatch];
    return isMatch;
}

/**
 * 比对身份证前两位是否合法
 * 二分法查找
 */
+(BOOL)binary_search:(int)targetValue
{
    const int len = 35;
    int areasArray[len] ={11,12, 13,14, 15,21, 22,23, 31,32, 33,34, 35,36, 37,41,42,43,44,45, 46,50, 51,52, 53,54, 61,62, 63,64,65,71, 81,82, 91};
    
    int low = 0;
    int high = len - 1;
    while(low <= high)
    {
        int middle = (low + high)/2;
        if(areasArray[middle] == targetValue)
            return YES;
        //在左半边
        else if(areasArray[middle] > targetValue)
            high = middle - 1;
        //在右半边
        else
            low = middle + 1;
    }
    //没找到
    return NO;
}


@end
